package com.msmall.base.util;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import com.msmall.base.cache.CacheFactory;
import com.msmall.base.cache.ICache;
import com.msmall.community.ApplicationManager;
import com.msmall.community.common.CommunityInitialize;
import com.msmall.community.common.model.UserAgent;
import com.msmall.community.common.service.UserAgentManager;

/**
 * 
 * @author zhzy
 *
 */
public final class UAUtil {
	public static String getUserAgentType(HttpServletRequest request) {
		String reqTelno = request.getHeader("x-up-calling-line-id");
		String userAgent = request.getHeader("User-Agent");
		/*
		//pc browser access: ua != null; mobile browser access: ua can be everything, null included
		if(null == userAgent) 
			return Constants.USER_AGENT_TYPE_HTML;
		if (reqTelno != null) {
			return Constants.USER_AGENT_TYPE_WML;
		}else {
			return getUserAgentType(userAgent);
		}
		*
		*/
		return getUserAgentType(userAgent);
	}

	private static String getUserAgentType(String userAgent) {
		if(StringUtil.nullOrBlank(userAgent)){
			return Constants.USER_AGENT_TYPE_HTML;
		}
		Iterator it = getUserAgents().iterator();
		boolean find = false;
		while (it.hasNext()) {
			UserAgent bean = (UserAgent) it.next();
			/*
			if(bean.getEnabled() != null){
				if(bean.getEnabled().compareTo(Short.valueOf((short)0)) == 0){
					continue;
				}
			}
			*/
			if (userAgent.toLowerCase().equalsIgnoreCase(bean.getAgentValue())) {
				find = true;
			}
		}
		if(!find){
			UserAgent newUA = new UserAgent();
			newUA.setAgentType(Constants.USER_AGENT_TYPE_UNKNOW);
			newUA.setAgentValue(userAgent);
			newUA.setEnabled(ConstantDB.UNAVALIABLE);
			UserAgentManager userAgentManager = (UserAgentManager) ApplicationManager.appContext.getBean("userAgentManager");
			userAgentManager.saveUserAgent(newUA);
			CommunityInitialize.refreshUserAgent();
		}
		return Constants.USER_AGENT_TYPE_HTML;
	}
	
	private static List getUserAgents(){
		ICache userAgents = CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON);
		List list = (List) userAgents.get(Constants.CACHE_KEY_USER_AGENT_LIST);
		if(null == list){
			CommunityInitialize.refreshUserAgent();
			list = (List) userAgents.get(Constants.CACHE_KEY_USER_AGENT_LIST);
		}
		return list;
	}
}
